package com.blog.service.impl;

import com.blog.constant.MsgConstant;
import com.blog.mapper.AdminMapper;
import com.blog.pojo.dto.AdminLoginDTO;
import com.blog.pojo.entity.Admin;
import com.blog.service.AdminService;
import com.blog.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    /**
     *  管理员登入
     * @param adminLoginDTO
     * @return
     */
    @Override
    public Admin login(AdminLoginDTO adminLoginDTO) {
        String adminName = adminLoginDTO.getAdminName();
        String password = adminLoginDTO.getPassword();

        //查询数据库中的账号信息
        Admin admin = adminMapper.getByAdminName(adminName);

        if (admin == null) { // 账号不存在
            return null;
        }

        //账号存在，比较密码
        password = DigestUtils.md5DigestAsHex(password.getBytes()); // 将校验数据转换成md5加密的字符串
        if ( !password.equals(admin.getPassword()) ) {// 密码错误，校验不通过
            return null;
        }

        //校验通过，返回账号数据
        return admin;
    }

    /**
     * 根据名字获取管理员信息
     * @return
     */
    @Override
    public Admin getAdminByName() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String adminName = (String) map.get("adminName");
        return adminMapper.getByAdminName(adminName);
    }
}
